<template>
  <el-row :gutter="20">
    <el-col :span="18">
      <div class="header-left">
        <el-button @click="openAddDialog" type="primary" :icon="Plus">添加</el-button>
        <el-button @click="handleDelete" type="danger" :icon="Delete">批量删除</el-button>
      </div>
    </el-col>
    <el-col :span="6">
      <div class="header-right">
        <el-input v-model="searchInput.userName" style="width: 200px" placeholder="请输入用户名" />
        <el-button @click="handleSearch" type="primary"><i-Search /></el-button>
      </div>
    </el-col>
  </el-row>
  <div>
    <DataList
      :columns="columns"
      :data-list="dataList"
      :pagination="pagination"
      @edit="openEditDialog"
      @delete="handleDelete"
      @selection-changed="handleSelectionChanged"
      @update:pagination="handlePaginationUpdate"
    />
    <Dialog ref="dialogRef" :dialog="isDialogVisible" :dialogConfig="dialogConfig" :fields="fields" :fieldInfo="fieldInfo" :rules="rules">
      <template #header>
        <span v-if="isAddVisible">添加用户</span>
        <span v-else>编辑用户</span>
      </template>
      <template #footer>
        <el-button @click="handleFormSumbit">确认</el-button>
      </template>
    </Dialog>
  </div>
</template>
<script setup>
import DataList from '@/components/datalist/DataList.vue'
import Dialog from '@/components/dialog/Dialog.vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import { ref, computed, onMounted, onBeforeMount } from 'vue'
import { useCounterStore } from '@/stores/counter.js'
import { useUserManStore } from '@/stores/admin/userman/index.js'
import { ElMessage } from 'element-plus'
/* DataList 父传子数据 */
// 定义表格列的数据
const columns = ref([
  { prop: 'userId', label: 'ID', width: '10' },
  { prop: 'userName', label: '用户名' },
  { prop: 'phone', label: '手机号' },
  { prop: 'password', label: '密码' },
  { prop: 'gender', label: '性别' },
  { prop: 'nickName', label: '昵称' },
  { prop: 'userIcon', label: '头像' },
  { prop: 'ifVip', label: 'VIP' },
  { prop: 'ifAdmin', label: '管理员' }
])
const dataList = ref([])
const pagination = ref({ page: 1, pageSize: 10, total: 0 })

/* Dialog 父传子数据 */
const isDialogVisible = ref(false) // 控制对话框的显示与隐藏
const dialogConfig = ref({ dialogHeight: '600px', dialogWidth: '600px' }) // 定义对话框配置
// 表单内容
const fields = computed(() => [
  { type: 'input', prop: 'userId', label: 'ID', disabled: true, placeholder: '提交后生成', width: '50%' },
  { type: 'input', prop: 'userName', label: '用户名', placeholder: '请输入用户名', width: '50%' },
  { type: 'input', prop: 'phone', label: '手机号', placeholder: '请输入手机号', width: '50%' },
  {
    type: 'input',
    prop: 'password',
    label: '密码',
    disabled: !isAddVisible.value,
    isPassword: true,
    placeholder: '请输入密码',
    width: '50%'
  },
  {
    type: 'radio',
    prop: 'gender',
    label: '性别',
    radios: [
      { label: '男', name: '男' },
      { label: '女', name: '女' }
    ],
    width: '50%'
  },
  { type: 'input', prop: 'nickName', label: '昵称', placeholder: '请输入昵称', width: '50%' },
  { type: 'input', prop: 'userIcon', label: '头像', placeholder: '请输入头像', width: '50%' },
  {
    type: 'radio',
    prop: 'ifVip',
    label: 'VIP',
    radios: [
      { label: 1, name: '是' },
      { label: 0, name: '否' }
    ],
    width: '50%'
  },
  {
    type: 'radio',
    prop: 'ifAdmin',
    label: '管理员',
    radios: [
      { label: 1, name: '是' },
      { label: 0, name: '否' }
    ],
    width: '50%'
  }
])
// 表单字段的默认值
const fieldInfo = ref({ userId: '', userName: '', phone: '', password: '', gender: '', nickName: '', userIcon: '', ifVip: '', ifAdmin: '' })
// 自定义规则
const rules = ref({
  userName: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
  phone: [{ required: true, message: '请填写手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请填写密码', trigger: 'blur' }]
})

/* 本界面 */
const dialogRef = ref(null) // 定义对话框的引用
const isAddVisible = ref(true) // 判断显示添加弹窗,还是编辑弹窗
const selectedRows = ref([]) // 定义一个响应式变量来存储选中行的数据
const searchInput = ref({
  userName: '' // 初始值为空字符串
})
const counterStore = useCounterStore() // 获取封装的方法
const userManStore = useUserManStore() // 获取封装的api
// 打开添加弹窗
const openAddDialog = () => {
  isAddVisible.value = true
  fieldInfo.value = { ...null } // 初始化表单
  dialogRef.value.openDialog()
}
// 打开编辑弹窗
const openEditDialog = (row) => {
  isAddVisible.value = false
  fieldInfo.value = { ...row } // 使用...拓展符创建一个新对象,便于激发dialog组件的侦听
  dialogRef.value.openDialog()
}
// 处理选中行数据变化事件
const handleSelectionChanged = (newSelectedRows) => {
  selectedRows.value = newSelectedRows // 更新响应式变量
}

/* 向后端发送请求 */
// 获取用户列表
const fetchData = async (formInfo) => {
  await userManStore
    .getUserList(formInfo)
    .then(({ data }) => {
      pagination.value.total = data.total
      dataList.value = data.rows
    })
    .catch((error) => {
      ElMessage.error(error.msg || '获取用户列表失败,请重试')
    })
}
// 组件挂载后获取用户信息
onMounted(() => {
  fetchData()
})
// 处理分页器更新
const handlePaginationUpdate = (pagination) => {
  fetchData(pagination) // 根据分页信息重新获取数据
}
// 添加/修改用户
const handleFormSumbit = async () => {
  const formData = await dialogRef.value.submitForm()
  if (!formData) {
    ElMessage.error('请先通过表单验证')
    return
  }
  if (isAddVisible.value) {
    // 如果为添加用户
    userManStore
      .postUser(formData) // 发送添加用户请求
      .then(async () => {
        ElMessage.success('添加成功')
        fetchData()
        dialogRef.value.closeDialog()
      })
      .catch((error) => {
        // console.log(error)
        ElMessage.error(error.msg || '登录失败(请联系管理员)')
      })
  } else {
    userManStore
      .putUser(formData) // 发送修改用户请求
      .then(async () => {
        ElMessage.success('修改成功')
        fetchData()
        dialogRef.value.closeDialog()
      })
      .catch((error) => {
        ElMessage.error(error.msg || '修改失败(请联系管理员)')
      })
  }
}
// 删除用户
const handleDelete = (row = null) => {
  // 若没有特定的行被指定，则是批量删除
  // 检查row是否为一个事件对象,使用instanceof操作符检查row是否是一个Event对象的实例(row可能是点击事件)
  if (row && row instanceof Event) {
    row.preventDefault()
    row = null
    // 此时为批量删除
    if (selectedRows.value.length === 0) {
      ElMessage.error('没有选中的用户进行删除')
      return
    }
  }
  const message = row ? '确认要删除该用户吗?' : '确认要删除选中的所有用户吗?'
  counterStore.confirmBox(message, '确认', '取消', 'error', () => {
    const rows = row || selectedRows.value
    userManStore
      .deleteUser(rows) // 发送删除用户请求
      .then(async () => {
        ElMessage.success('删除成功')
        fetchData()
      })
      .catch((error) => {
        ElMessage.error(error.msg || '删除失败,请重试')
      })
  })
}
// 搜索用户
const handleSearch = () => {
  fetchData(searchInput.value)
  ElMessage.success('搜索成功')
}
</script>
<style scoped>
.header-right {
  display: flex;
}
:deep(.el-input__wrapper) {
  margin-right: 5px;
}
</style>
